var indicatorOptions = [
  {label: 'Linear', title: 'Linear', value: 'linear'},
  {label: 'Simple Moving Average', title: 'Simple Moving Average', value: 'SMA'},
  {label: 'Exponential Moving Average', title: 'Exponential Moving Average', value: 'EMA'},
  {label: 'MACD', title: 'MACD', value: 'MACD'},

];

function addSeriesSelect( seriesName ) {
	var options = document.getElementById( "seriesNames");
    options.appendChild(new Option( seriesName, seriesName ) );	
    options.disabled = false;
}

var seriesItems = [ "zoom-open", "zoom-close" , "series-customize"];

function onSeriesSelect( selectedValue) {
	var enabled = false;
	if ( selectedValue != "") {
		enabled = true;
	}
	for ( var index = 0; index < seriesItems.length; index++ ) {
		$( "#" + seriesItems[index] ).prop( "disabled", !enabled );
	}

	 $('#indicators').multiselect( enabled ? "enable" : "disable");
	 if ( enabled ) {
		switchSeriesName( selectedValue ); 	
	 }

	
}



function getIndicatorSeriesName( seriesName, indicatorName ) {
	return seriesName+"-"+indicatorName;
}

function getCurrentSeriesName() {
	return $('#seriesNames').val();

}

/**
 * Add series if the indicator series is not there
 */
function indicatorsChanged() {
	var seriesName = $('#seriesNames').val();
	var series = findSeriesIndex( seriesName );
	var selected = $('#indicators').val();
	if ( selected ) {
		for ( var index = 0; index < selected.length; index++ ) {
			var indicatorName = selected[ index ];
			var indicatorSeriesName = seriesName+"-"+indicatorName;
			var indicatorSeriesIndex = findSeriesIndex( indicatorSeriesName );
			if (  indicatorSeriesIndex < 0 ) {
				addIndicatorSeries( seriesName, indicatorName, indicatorSeriesName );	
			}
		}		
	}

	//remove all deselected indicators
	for ( var index = 0; index < indicatorOptions.length; index++ ) {
		var possibleValue = indicatorOptions[ index ].value;
		if ( selected == null || selected.indexOf( possibleValue ) < 0 ) {
			removeSeries( findSeriesIndex ( seriesName + "-" + possibleValue));
		}
	}
}

function addIndicatorSeries( seriesName, indicatorName, indicatorSeriesName) {
	 console.log( "Adding indicator series: " + indicatorSeriesName + " Algo: " + indicatorName );
	 var series = getSeries( getCurrentSeriesName() );
	 var seriesOptions = {
	 		id: indicatorSeriesName,
			name: indicatorSeriesName,
	        linkedTo: seriesName,
	        showInLegend: true,
	        enableMouseTracking: true,
	        showCurrentPriceIndicator: false,
	        type: "trendline",
	        algorithm: indicatorName
	 };

	 switch( indicatorName ) {
	 	case "SMA":
	 	case "EMA":
	 		//seriesOptions.yAxis = series.yAxis;
	 		seriesOptions['periods'] = 5;
	 		break;
	 	case "MACD":
	 		newAxisId = getYAxisId("MACD");
	 		if ( highCharts.get( newAxisId ) == null ) {
	 			var axisOptions = {
	 				"left" : false,
	 				paneIndex: 1
	 			};
	 			var newAxis = assignYAxis( "MACD", axisOptions);
	 		}
 			seriesOptions.yAxis = newAxisId;

	 		break;
	 }

	var indicatorSeries = highCharts.addSeries(seriesOptions);


}


function switchSeriesName( seriesName ) {

	$("#modal-label").text( seriesName );
	loadSeriesColor( seriesName );

	resetIndicators();
	var indicators = $('#indicators');
	indicators.multiselect('deselectAll', false );
	var selectedIndicators = [];
	for ( var index = 0; index < indicatorOptions.length; index++ ) {
		var indicatorName = indicatorOptions[index].value;
		if ( getSeries( getIndicatorSeriesName( seriesName, indicatorName ) ) ) {
			selectedIndicators.push( indicatorName );
		}
	}
	if ( selectedIndicators.length > 0 ) {
		indicators.multiselect( 'select', selectedIndicators );
	}
	indicators.multiselect('updateButtonText')
	populateCustomizedSeriesOptions();
}

function loadSeriesColor( seriesName ) {
		$("#seriesColor").val( '' );
}

function populateCustomizedSeriesOptions() {
	var currentSeriesName = getCurrentSeriesName();
	var series = getSeries( currentSeriesName );
	if ( !series ) return;
	var separateYAxis = false;
	if ( series.yAxis.userOptions.index != 0 ) {
		separateYAxis = true;
	}
	$("#separateYAxis").prop( "checked", separateYAxis);
	
	$("#yaxisType").val( series.yAxis.options.type );
	$("#yaxisOrientation").val( series.yAxis.options.opposite.toString() );
	
	
}

function updateLinkedSeriesYAxisIndex( series, newYAxisIndex ) {
	if ( !series.linkedSeries || series.linkedSeries.length == 0 ) return;
	for ( var index = 0; index < series.linkedSeries.length; index++ ) {
		var series = series.linkedSeries[ index ];
		var yAxisObj = highCharts.get( series.yAxis );
		if ( yAxisObj.userOptions.index != newYAxisIndex ) {
			console.info( "Moving Series " + series.name + " to Axis: " + newYAxisIndex );
			series.update( { "yAxis" : yAxisObj.options.id }, false );
		}
	}
}

function separateCurrentYAxis( separate ) {
	var seriesName = getCurrentSeriesName();
	var series = getSeries( seriesName );
	var axisOrientation = $("#yaxisOrientation").val();
	var axisOptions = {
		axisType: $("#yaxisType").val(),
		left: axisOrientation == "false"
	};
	var lineColor = $("#seriesColor").val();
	if ( lineColor != "" ) {
		axisOptions['lineColor'] = lineColor;
	} else {
		axisOptions['lineColor'] = series.color;
	}


	var newAxis = false;
	if ( series  ) {
		console.log( "Series: " + seriesName + separate ? "Separating yAxis"  : "Reattaching yAxis" );
		var created = false;
		if ( separate ) {
			if ( series.yAxis.userOptions.index == 0 ) {
				var yAxis = assignYAxis( seriesName, axisOptions );
				if ( series.yAxis != yAxis ) {
					series.update({
							"yAxis" : yAxis,
					}, false);
					var yAxisObject = highCharts.get( yAxis );

					updateLinkedSeriesYAxisIndex( series, yAxisObject.options.index );
				}
				created = true;
			}
			
		} else {
			if ( series.yAxis ) {
				var oldAxisId = series.yAxis.options.id;
				series.update({
					"yAxis" : 0
				}, false);				
				removeYAxis( oldAxisId );
				updateLinkedSeriesYAxisIndex( series, 0 );
			}
		}
		if ( ! created ) { //apply options
			var currentTitle = series.yAxis.options.title.text;
			var axisOptions = createAxisOptions( currentTitle, axisOptions )
			if ( series.yAxis.options.index == 0 ) {
				delete axisOptions[ 'id']; 
				//default one has an id already
			}
			series.yAxis.update( axisOptions, false );

		}
	}
	recalculateYAxisOffsets();
}



function updateYAxis() {
	separateCurrentYAxis($("#separateYAxis").is(':checked'));
	var seriesName = getCurrentSeriesName();
	var series = getSeries( seriesName );
	var axisType = $("#yaxisType").val();
	if ( series.yAxis ) {
		var axis = series.yAxis;
		if ( axis && axis.userOptions.type != axisType ) {
			axis.update({ 
					type: axisType
				});
		}
	}
}

function updateSeriesColor() {
	var seriesName = getCurrentSeriesName();
	var selectedColor = $("#seriesColor").val();
	if ( selectedColor != "" ) {
		console.log("Changing series: " +seriesName + " color to " + selectedColor );
		var series = getSeries( seriesName );
		series.update( { color: selectedColor }, false );
	}
}

function applySeriesUpdates() {

	updateYAxis();
	updateSeriesColor();
	structureRedraw();

}

function resetIndicators() {
		$('#indicators').multiselect({ 
			nonSelectedText: "Indicators",
			onChange: function(element, checked) { indicatorsChanged(); },
		});	
}

/**
 * Turn off last price indicators and hovers if requested
 */
function handleExtras( enabled ) {
	highCharts.options.performance.currentPriceIndicator = enabled;
	highCharts.options.performance.seriesTooltips = enabled;
	setSeriesTooltips( enabled );
	highCharts.redraw();
}

function setSeriesTooltips( enabled ) {
	var allSeries = getAllSeries( highCharts );
	for ( var index = 0; index < allSeries.length; index++ ) {
		var series = allSeries[ index ];
		series.update( { enableMouseTracking : enabled }, false);
	}
}
